package com.alipay.web.servlet;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;


import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.NOTIFY_URL;
import static com.alipay.api.AlipayConstants.RETURN_URL;

@WebServlet("/pay/alipay")
public class payServlet extends BaseServlet {
    //appid
    private final String APP_ID = "9021000136670922";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCPivL21VKMZwf69j4bofnEmlEVfRSGsEix8NBgB2ojv8gTfIWdNHwOSqEjZph3WfPXUqUdOWybq27lVQrjCz1jg2lu+ySxv+Sv+g0B+8ThGd+EPh+uqfb5pD9mD8Sqv6AqjV5haUKn2nGkhTQVgtkRyG5R6Sii0EdL4eLyNx6ImbBoaUSHDTVc9oX5f0IuHzX4FLTlZpLbCM9rDGtm2wBSBqkN2SEyeExOYeS9LNw2pAGp+5HduQPVA7+FOPLi1CASDZYQXB1edcdXcwvVSdH84OfL8bTC8L+fbB+lA5iHbux2CEvyFYVjMmHwJ0qoRWlPF9f8F/i5tzE2dcnIBpzZAgMBAAECggEAN5NWqpbBVTb28gWw2kYGTEZrKmS5M8TBAJP6OZPlVl4Eevb1TH5roaTnaqtoUJ11OWL4Jq57DHJ9hzE7+9f4NrVEdwGpnWBsjG3F54SxH25DChJ7dca8pr8fBMcKIAn9WzxM1G5Krm53HXmtRr7YiHgProsVfqQhVpHoqlsI6V3zEvhRNX1TyhgEZvABs6H0DyIt/WtCdw7TypwmcCCvAOxR5U+enGN/sfZTskpGEVoy2+hSOOGYCxWX8UzQ4zK6u3LpNmLk1fVCqxKFy8t8PyCz28JEquL101jdwsFz/oAhvv9T9TlXU1vmI9wv2EPIRXqFgP9ckbeGTpvVDxs2YQKBgQDNUajAZ5Cw7Zc1kq73jP3Zrymwn6aOmGi3wifphteSmMKY7HUuOVqawt73d3SfQ45Qw/i6L1UkkOQH87uy9Zp1yC7d+qedn3WRRIPJKw+lB9KK2mcJyBc6b/0ItlqZ32j5912fQjKaztyvWYlh9HYhXXfsSk4pgmqriB7NV3aebQKBgQCy+ZSgeag1064GIu4mEf13eVfYoZacvkORLZrTjae1I1liDrCv9iDmqMT+VjnHMZgKJTJ2KxfFZBHN0NdIXGkf9zQqtCSJLk1tN6q/M4GgP7nOhYbevs2l+L6FDFR2Aq6soG8ehspk8+f+gDxpRdzgLNbqluwoMNIfEuf9UWzEnQKBgE9CLaWQlS9nmE6LAFX5rGjjEHHpP2+ecBY3shaZAhDKPZyw8w9T/qDthwr6px9wAbk13YdqDDEgaZaURSnxW54KF+WDBD95tfXNAB6hK9nmKiWF5+7DugvJ/WDmnBT4RFryXcbD1CskndZm9vzEVPHOViP2DzRA7xKmalWUZOsFAoGAe25hMGN2vNimNhk1ARB7LECFcyPOCX+2fZNkKe6R8PzWEihrdo9alXljkrzI0DXF04lfydtiY4HmPXmAX6lL3v3P/nuKjwld4Kr5mS/egDQy4tl38HrKvWJVktC0F0c2TFvBBt6TCxijsQOjpj7GW9zQw60eZYF2CHQzhqL3TokCgYA0mqu6xyZd2fE7ZbeN8J0hT/QncUg4t1pOjoFOfkyL5vNSr4aydTUwRM7mQJ3ZaMHD1OL3glXoMZ3MoCjPIR9Sq5i72DDNj6TRDHE4d3HiXbl89Ir0i3DdxgvwJmL2vRWuT7o82+Ux9TigqrtmP3N3U8N2VI6V9I4tFlsIvTg4mA==";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjipaNHVCI3kUT4yKtj0QT7LCrZPeVxRriubc15lwLE5B8TYIkmf4Tm4/7o3pLqCxSziYZYNP4UOmBfgQchdx5ZyH/c3Q2HF+pA7mTmfUe7FW0RQ+/b79QzSIRzoW9/Cjn2r3qaqN4EZp485vNS9mctJp17G9SmUNJYnJPs7kjjNVRzl2smf1qq66FXFUT/tdw0gYyxSaC2RFKATAKtIqmZld/gwhz7cMqkn3c+pmkwyzarYcl6TO2jR+CC0aeSjW3FjKDwMJIO0aWxLrLprZwstQJTNM+VP8/Yhp+kYYO8Y+vzPrFVJE6ENwIdgIEkZtuyNhFMuOqbrl4zA1iUOSPwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://zsfkc6.natappfree.cc/alipay_war/hello.index";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://zsfkc6.natappfree.cc/alipay_war/hello.index";

    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    /*@ResponseBody
    @RequestMapping("")
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") float dona_money,
                         @RequestParam("dona_id") int dona_id) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",dona_id);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,"ghjk");
    }*/
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

}
